package football.core;

import playn.core.Json;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by tol on 29.04.2014.
 */
public abstract class JsonMap <TValue extends JsonValue> extends HashMap<String, TValue> implements JsonValue {

    @Override
    public void apply(Json.Object jObj){
        ArrayList<String> toRemove = new ArrayList<String>();
        if(jObj==null){
            for (String key : keySet()) {
                toRemove.add(key);
            }
        }
        else {

            for (String key : keySet()) {
                if (!jObj.containsKey(key))
                    toRemove.add(key);
            }


            for (String key : jObj.keys()) {
                Json.Object subObj = jObj.getObject(key);
                if (!containsKey(key)) {
                    put(key, createItem(subObj));
                }
                get(key).apply(subObj);
            }
        }
        for (String key : toRemove) {
            onRemoveItem(remove(key));
        }
    }

    protected abstract TValue createItem(Json.Object jObj);
    protected void onRemoveItem(TValue item){};



}
